public class HashBucket {

    //哈希桶中的节点
    static class Node{

        public int key;

        public int val;

        public Node next;

        public Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }

    //存放节点的数组
    public Node[] array;

    //元素个数
    public int usedSize;

    public HashBucket(){
        array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;
        Node cur = array[index];

        //先遍历一遍整体链表 是否存在当前key
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //没有这个key
        Node node = new Node(key, val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if (loadFactor() >= 0.75) {
            resize();
        }
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

    /**
     * 扩容的时候需要注意什么？
     *    把所有的元素都重新进行哈希
     */
    private void resize(){
        Node[] tmpArray = new Node[array.length*2];
        //遍历原来的数组 将数组中的元素重新哈希到新的数组当中
        for(int i = 0; i < array.length; i++){
            Node cur = array[i];
            while(cur != null){
                //计算新的位置
                int newIndex = cur.key % tmpArray.length;
                //记录当前节点的下一个节点
                Node curNext = cur.next;
                cur.next = tmpArray[newIndex];
                tmpArray[newIndex] = cur;
                cur = curNext;
            }
        }
        array = tmpArray;
    }

    private double loadFactor(){
        return usedSize * 1.0 / array.length;
    }



}
